package com.example.demo.mapper;

import com.example.demo.entity.User;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface UserMapper {
    @Select("SELECT id, username, password, email, avatar, gender, bio, birthday, " +
            "created_at AS createdAt, updated_at AS updatedAt " +
            "FROM user WHERE account = #{account}")
    User findByAccount(String account);
    //创建用户
    @Insert("INSERT INTO user (account, password, email,username) " +
            "VALUES (#{account}, #{password}, #{email},#{username})")
    int insertUser(User user);

    // 根据用户 ID 查询用户
    @Select("SELECT id, username, password, email, avatar, gender, bio, birthday, " +
            "created_at AS createdAt, updated_at AS updatedAt " +
            "FROM user WHERE id = #{id}")
    User findById(Long id);
    //更新密码
    @Update("UPDATE user SET password = #{password} WHERE id = #{id}")
    int updatePassword(Long id, String password);
    //更改资料
    @Update("UPDATE user SET "+
    "username = COALESCE(#{user.username},username),"+
    "avatar = COALESCE(#{user.avatar},avatar),"+
    "gender = COALESCE(#{user.gender},gender),"+
    "birthday = COALESCE(#{user.birthday},birthday),"+
    "bio = COALESCE(#{user.bio},bio)"+
    "WHERE id = #{userId}")
    int updateUserInfo(Long userId, User user);
    //更改头像
    @Update("UPDATE user SET avatar = #{avatarUrl} WHERE id = #{userId}")
    int updateUserAvatar(Long userId, String avatarUrl);
    // 根据用户名模糊查询用户
    @Select("SELECT id, username, password, email, avatar, gender, bio, birthday, " +
            "created_at AS createdAt, updated_at AS updatedAt " +
            "FROM user WHERE username LIKE CONCAT('%', #{username}, '%')")
    List<User> findByUsername(@Param("username") String username);
    //根据帖子id获取作者
    @Select("SELECT u.* FROM user u JOIN post p ON u.id = p.user_id WHERE p.id = #{postId}")
    User findPostAuthorByPostId(Long postId);
}

